package com.centaline.androidsalesblog.fragments;


import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.WebActivity;
import com.centaline.androidsalesblog.activities.map.MainMapActivity;
import com.centaline.androidsalesblog.activities.newest.NewEstActListActivity;
import com.centaline.androidsalesblog.activities.newest.NewEstListActivity;
import com.centaline.androidsalesblog.activities.sale.EsfEstateListActivity;
import com.centaline.androidsalesblog.activities.sale.EsfSaleListActivity;
import com.centaline.androidsalesblog.activities.sale.MetroListActivity;
import com.centaline.androidsalesblog.activities.sale.RentListActivity;
import com.centaline.androidsalesblog.activities.sale.SaleListActivity;
import com.centaline.androidsalesblog.activities.sale.SchoolListActivity;
import com.centaline.androidsalesblog.activities.sale.StoreListActivity;
import com.centaline.androidsalesblog.activities.search.SearchActivity;
import com.centaline.androidsalesblog.adapter.AdAdapter;
import com.centaline.androidsalesblog.adapter.HomeMainAdapter;
import com.centaline.androidsalesblog.adapter.HomeMenuAdapter;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.base.BaseFragment;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.events.CityInfoUpdate;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.iml.RetryRequest;
import com.centaline.androidsalesblog.model.businissobject.AdBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.ModuleDo;
import com.centaline.androidsalesblog.model.responseobject.AdRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.service.BaseDataService;
import com.centaline.androidsalesblog.widgets.FixGridView;
import com.centaline.androidsalesblog.widgets.FixListView;
import com.centaline.androidsalesblog.widgets.vpinfinite.IndicatorViewEx;
import com.centaline.androidsalesblog.widgets.vpinfinite.SliderLayoutEx;
import com.centanet.framework.base.AbstractActivity;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.utils.PatternFormat;
import com.trello.rxlifecycle.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements OnClickListener {

    /*标题栏*/
    private AppBarLayout appbar;
    private AppCompatTextView atv_city, atv_search, atv_error;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private RelativeLayout rl_home_search;
    private ImageView img_home_voice;

    private LinearLayout ll_content, ll_default;
    /*中间模块*/
    private FixGridView fixGridView;
    private FixListView fixListView;

    /*广告*/
    private ViewStub vs_ad;
    private FrameLayout fl_ad;
    private SliderLayoutEx sl_ad;
    private IndicatorViewEx ind_ad;

    private HomeMainAdapter homeMainAdapter;
    private HomeMenuAdapter homeMenuAdapter;
    private ArrayList<ModuleDo> homeMainModules = new ArrayList<>();
    private ArrayList<ArrayList<ModuleDo>> homeMenuModules = new ArrayList<>();
    private ArrayList<AdBo> adBoArrayList = new ArrayList<>();

    private RetryRequest retryRequest;
    private DrawableRequestBuilder<String> requestBuilder;
    private int lastVerticalOffset = -1;
    private int appbarTotalScrollRange;
    private int city_width;
    private int search_width;
    private int search_leftMargin;
    private int search_bottomMargin;
    private int screenWidth;

    private boolean exChangeCityEnable;

    public void setRetryRequest(RetryRequest retryRequest) {
        this.retryRequest = retryRequest;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void findViews(View view) {
        appbar = (AppBarLayout) view.findViewById(R.id.appbar);
        atv_city = (AppCompatTextView) view.findViewById(R.id.atv_city);
        atv_search = (AppCompatTextView) view.findViewById(R.id.atv_search);
        collapsingToolbarLayout = (CollapsingToolbarLayout) view.findViewById(R.id.collapsingToolbarLayout);
        rl_home_search = (RelativeLayout) view.findViewById(R.id.rl_home_search);
        img_home_voice = (ImageView) view.findViewById(R.id.img_home_voice);

        ll_content = (LinearLayout) view.findViewById(R.id.ll_content);
        ll_default = (LinearLayout) view.findViewById(R.id.ll_default);
        fixGridView = (FixGridView) view.findViewById(R.id.fixGridView);
        fixListView = (FixListView) view.findViewById(R.id.fixListView);
        atv_error = (AppCompatTextView) view.findViewById(R.id.atv_error);

        vs_ad = (ViewStub) view.findViewById(R.id.vs_ad);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
    }

    @Override
    protected void initView() {
        ll_default.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                atv_error.setVisibility(View.GONE);
                if (retryRequest != null)
                    retryRequest.retry();
            }
        });
        final CollapsingToolbarLayout.LayoutParams searchLayoutParams =
                (CollapsingToolbarLayout.LayoutParams) rl_home_search.getLayoutParams();
        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (lastVerticalOffset == verticalOffset)
                    return;
                lastVerticalOffset = verticalOffset;
                if (appbarTotalScrollRange == 0) {
                    /*获取最大范围*/
                    appbarTotalScrollRange = appbar.getTotalScrollRange();
                }
                if (city_width != atv_city.getWidth()) {
                    city_width = atv_city.getWidth();
                }
                if (search_width == 0) {
                    search_width = rl_home_search.getWidth();
                    search_leftMargin = searchLayoutParams.leftMargin;
                    search_bottomMargin = searchLayoutParams.bottomMargin;
                }
                final int percent = (appbarTotalScrollRange + verticalOffset) * 100 / appbarTotalScrollRange;
                searchLayoutParams.setMargins(search_leftMargin +
                                (city_width + search_leftMargin * 2) * (100 - percent) / 100,
                        searchLayoutParams.topMargin,
                        searchLayoutParams.rightMargin,
                        search_bottomMargin);
                collapsingToolbarLayout.updateViewLayout(rl_home_search, searchLayoutParams);
            }
        });
        atv_city.setOnClickListener(this);
        rl_home_search.setOnClickListener(this);
        img_home_voice.setOnClickListener(this);

        requestBuilder = GlideLoad.init(this);
        homeMainAdapter = new HomeMainAdapter(getActivity(), requestBuilder, homeMainModules);
        fixGridView.setAdapter(homeMainAdapter);
        fixGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectModule(homeMainModules.get(position));
            }
        });

        homeMenuAdapter = new HomeMenuAdapter(getActivity(), requestBuilder, homeMenuModules,
                new HomeMenuAdapter.MenuItemClick() {
                    @Override
                    public void itemClick(ModuleDo moduleDo) {
                        selectModule(moduleDo);
                    }
                });
        fixListView.setAdapter(homeMenuAdapter);
        delay();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (sl_ad != null && sl_ad.getPagerAdapter() != null) {
            sl_ad.pauseAutoCycle();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (sl_ad != null && sl_ad.getPagerAdapter() != null && sl_ad.getRealCount() > 1) {
            sl_ad.startAutoCycle();
        }
    }

    /**
     * 刷新界面
     *
     * @param refreshType {@link com.centaline.androidsalesblog.service.BaseDataService.UpdateResult}
     * @see com.centaline.androidsalesblog.service.BaseDataService.UpdateResult
     */
    public void refreshUi(int refreshType) {
        switch (refreshType) {
            case BaseDataService.UpdateResult.Error:
                if (homeMainModules.size() == 0 && homeMenuModules.size() == 0) {
                    ll_content.setVisibility(View.GONE);
                    ll_default.setVisibility(View.VISIBLE);
                    atv_error.setVisibility(View.VISIBLE);
                }
                break;
            case BaseDataService.UpdateResult.NewData:
                delay();
                break;
            case BaseDataService.UpdateResult.Keep:
                if (exChangeCityEnable) {
                    exChangeCityEnable = false;
                    delay();
                }
                break;
            default:
                break;
        }
    }

    private void delay() {
        Observable.interval(0, 1, TimeUnit.SECONDS).take(1)
                .compose(this.<Long>bindUntilEvent(FragmentEvent.DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        refreshUi();
                    }
                });
    }

    /**
     * 刷新页面
     */
    public void refreshUi() {
        if (TextUtils.isEmpty(AppConstant.CityCode)) {
            updateCityInfo(0);
            return;
        }
        atv_city.setText(AppConstant.CityName);
        Observable.create(new Observable.OnSubscribe<List<ModuleDo>>() {

            @Override
            public void call(Subscriber<? super List<ModuleDo>> subscriber) {
                subscriber.onNext(DataSupport.where("cityCode = ?", AppConstant.CityCode).find(ModuleDo.class));
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<ModuleDo>>() {
                    @Override
                    public void call(List<ModuleDo> moduleDos) {
                        if (moduleDos == null || moduleDos.size() == 0) {
                            updateCityInfo(4);
                            return;
                        }
                        homeMainModules.clear();
                        homeMenuModules.clear();
                        final ArrayList<ModuleDo> menu1 = new ArrayList<>();
                        final ArrayList<ModuleDo> menu2 = new ArrayList<>();
                        for (ModuleDo moduleDo : moduleDos) {
                            if ("1".equals(moduleDo.getParentId())) {
                                homeMainModules.add(moduleDo);
                            } else if ("2".equals(moduleDo.getParentId())) {
                                menu1.add(moduleDo);
                            } else if ("3".equals(moduleDo.getParentId())) {
                                menu2.add(moduleDo);
                            }
                        }
                        if (menu1.size() > 0) {
                            homeMenuModules.add(menu1);
                        }
                        if (menu2.size() > 0) {
                            homeMenuModules.add(menu2);
                        }
                        homeMainAdapter.notifyDataSetChanged();
                        homeMenuAdapter.notifyDataSetChanged();
                        if (homeMainModules.size() > 0 || homeMenuModules.size() > 0) {
                            ll_content.setVisibility(View.VISIBLE);
                            ll_default.setVisibility(View.GONE);
                            adRequest();
                        } else {
                            ll_content.setVisibility(View.GONE);
                            ll_default.setVisibility(View.VISIBLE);
                        }
                        atv_error.setVisibility(View.GONE);
                        bizUnit();
                        updateCityInfo(2);
                    }
                });
    }

    /**
     * 广告请求
     */
    private void adRequest() {
        RxRequest.ad(getClass())
                .subscribe(new Subscriber<AdRo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(AdRo adRo) {
                        adBoArrayList.clear();
                        if (adRo.getList() != null) {
                            adBoArrayList.addAll(adRo.getList());
                        }
                        if (initAdViews()) {
                            fl_ad.setVisibility(adBoArrayList.size() > 0 ? View.VISIBLE : View.GONE);
                            sl_ad.setPagerAdapter(new AdAdapter(getContext(),
                                    adBoArrayList, requestBuilder,
                                    new RecyclerViewItemOnClickListener<AdBo>() {
                                        @Override
                                        public void onItemOnClick(AdBo adBo, int tag) {
                                            Matcher matcher = Pattern.compile(PatternFormat.HttpUrl).matcher(adBo.getTargetUrl());
                                            baiduEvent("A_Click");
                                            while (matcher.find()) {
                                                startActivity(new Intent(getActivity(), WebActivity.class)
                                                        .putExtra(ExtraConstant.WebUrl, adBo.getTargetUrl()));
                                            }
                                        }
                                    }));
                            ind_ad.setViewPager(sl_ad);
                            if (adBoArrayList.size() > 1) {
                                sl_ad.startAutoCycle();
                            } else {
                                sl_ad.pauseAutoCycle();
                            }
                        }
                    }
                });
        updateCityInfo(3);
    }

    /**
     * 初始化广告
     */
    private boolean initAdViews() {
        if (getView() == null)
            return false;
        if (vs_ad != null) {
            vs_ad.inflate();
            fl_ad = (FrameLayout) getView().findViewById(R.id.fl_ad);
            sl_ad = (SliderLayoutEx) getView().findViewById(R.id.sl_ad);
            ind_ad = (IndicatorViewEx) getView().findViewById(R.id.ind_ad);
            ViewGroup.LayoutParams layoutParams = fl_ad.getLayoutParams();
            layoutParams.height = screenWidth * 80 / 290;
            fl_ad.setLayoutParams(layoutParams);
        }
        return true;
    }

    /**
     * 模块选择
     */
    private void selectModule(ModuleDo moduleDo) {
        final int type = moduleDo.getType();
        switch (type) {
            case 10://新房列表
                startActivity(new Intent(getActivity(), NewEstListActivity.class));
                baiduEvent("D_Click");
                break;
            case 11://新房详情
                break;
            case 12://新房优惠活动列表
                startActivity(new Intent(getActivity(), NewEstActListActivity.class)
                        .putExtra(AbstractActivity.TITLE_ACTIVITY, moduleDo.getName()));
                baiduEvent("I_Click");
                break;
            case 13://新房优惠活动详情
                break;
            case 20://二手房列表
                startActivity(new Intent(getActivity(), SaleListActivity.class)
                        .putExtra(ExtraConstant.TARGET_POST, moduleDo.getTarget()));
                baiduEvent("C_Click");
                break;
            case 21://二手房详情
                break;
            case 22://热卖房源
                startActivity(new Intent(getActivity(), SaleListActivity.class)
                        .putExtra(BaseActivity.TITLE_ACTIVITY, moduleDo.getName())
                        .putExtra(ExtraConstant.HOT_POST, true));
                break;
            case 23://地铁房
                startActivity(new Intent(getActivity(), MetroListActivity.class)
                        .putExtra(AbstractActivity.TITLE_ACTIVITY, moduleDo.getName()));
                baiduEvent("G_Click");
                break;
            case 24://学区房
                startActivity(new Intent(getActivity(), SchoolListActivity.class)
                        .putExtra(AbstractActivity.TITLE_ACTIVITY, moduleDo.getName()));
                baiduEvent("H_Click");
                break;
            case 25://小区二手房
                if (!TextUtils.isEmpty(moduleDo.getTarget()) &&
                        moduleDo.getTarget().contains(",")) {
                    String[] targets = moduleDo.getTarget().split(",");
                    startActivity(new Intent(getContext(), EsfSaleListActivity.class)
                            .putExtra(BaseActivity.TITLE_ACTIVITY, targets[1])
                            .putExtra(ExtraConstant.CestCode, targets[0]));
                }
                break;
            case 30://租房列表
                startActivity(new Intent(getActivity(), RentListActivity.class));
                baiduEvent("E_Click");
                break;
            case 31://租房详情
                break;
            case 40://门店列表
                startActivity(new Intent(getActivity(), StoreListActivity.class)
                        .putExtra(AbstractActivity.TITLE_ACTIVITY, moduleDo.getName()));
                baiduEvent("K_Click");
                break;
            case 50://webView页面
                startActivity(new Intent(getActivity(), WebActivity.class)
                        .putExtra(AbstractActivity.TITLE_ACTIVITY, moduleDo.getName())
                        .putExtra(ExtraConstant.WebUrl, moduleDo.getTarget()));
                break;
            case 60://小区列表
                startActivity(new Intent(getActivity(), EsfEstateListActivity.class));
                baiduEvent("J_Click");
                break;
            case 70://经纪人列表
                break;
            case 102://地图找房
                startActivity(new Intent(getContext(), MainMapActivity.class));
                baiduEvent("F_Click");
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.atv_city:
                exChangeCityEnable = true;
                updateCityInfo(1);
                baiduEvent("B_Click");
                break;
            case R.id.rl_home_search:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                baiduEvent("L_Click");
                break;
            case R.id.img_home_voice:
                startActivity(new Intent(getActivity(), SearchActivity.class)
                        .putExtra(ExtraConstant.SearchVoice, true));
                baiduEvent("M_Click");
                break;
            default:
                break;
        }
    }

    /**
     * 更新城市信息
     */
    private void updateCityInfo(int status) {
        EventBus.getDefault().post(new CityInfoUpdate(status));
    }

    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        atv_search.setText(bizUnitDo.isEnableErshoufang() ?
                                getString(R.string.home_text_search) :
                                "请输入楼盘名、板块");
                    }
                });
    }
}
